package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.pi.common.CodesConstants;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.common.vo.act.PalletizeChangeData;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.PalletizeActionDto;
import com.pi.wms.dto.act.TaskActionDto;
import com.pi.wms.dto.inventory.InventoryLabelDto;
import com.pi.wms.entity.*;
import com.pi.wms.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Controller
public abstract class BaseAsnDetailsController<T, ID extends Serializable> extends BaseCrudController<T, ID> {


    @Autowired
    protected AsnService headerService;
	@Autowired
    protected AsnDetailsService service;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private DivisionService divisionService;

    @Autowired
    protected LocationService locationService;

	@Autowired
	protected ParameterService parameterService;

	@Autowired
	private InventoryDetailsService inventoryService;

    @Autowired
	protected PalletizeService palletizeService;

    @Autowired
    protected TaskService taskService;

	@Autowired
	protected PrintTaskService printTaskService;

    @Autowired
    private WasCustomWorkService customWorkService;
	
	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		Long userId = SecurityUtils.getLoginUserId();
		query.put("userId", userId.toString());
		super.prepareDatatableConditions(query, input);
	}
	
	@Override
	@GetMapping(value = { "", "/{headerId}" })
	public String list(Model model, @PathVariable Map<?, ?> params, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		TwaDocAsnHeader header = this.getHeader(params);
		model.addAttribute("r", header);
		if (header!=null){
			Map<String,Object> maps=new HashMap<String,Object>();
			maps.put("m.headerId", header.getId());
			model.mergeAttributes(maps);
		}
		return super.list(model, params, request, redirectAttributes);
	}
	
    @Override
	@GetMapping(value = { "add" })
    public String add(Model model, HttpServletRequest request) {
		TwaDocAsnHeader header =this.getHeader(request);
		model.addAttribute("r", header);
		//model.addAttribute("m.headerId", header.getId());
        String flag=null;
		if (header!=null){
			model.addAttribute("headerId", header.getId());
            //
            flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_ASN);
            if  ((CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag))
                    && (!WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
                this.addWarnMessage(model, new String[]{"单证已经开始作业，不能修改!"});
                return this.redirect("/"+String.valueOf(header.getId()));
            }
		}
        return super.add(model, request);
    }
    
    @Override
    @GetMapping(value = { "edit/{id}" })
    public String edit(@ModelAttribute("m") T m, Model model, HttpServletRequest request,
                       RedirectAttributes redirectAttributes) {
        TwaDocAsnHeader header =this.getHeader(request);
        model.addAttribute("r", header);
        String flag=null;
        if (header!=null){
            model.addAttribute("headerId", header.getId());
            //
			flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_ASN);
			if  ((CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag))
					&& (!WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
				this.addWarnMessage(redirectAttributes, new String[]{"单证已经开始作业，不能修改!"});
				return this.redirect("/"+String.valueOf(header.getId()));
			}
        }
        return super.edit(m, model, request, redirectAttributes);
    }


	@PostMapping("linerecv")
	public String receiveByDocLines(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
						  RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		Set<String> conts=new HashSet<String>();
		TwaDocAsnDetails det=null;
		TwaDocAsnHeader header=null;
		String contnum="";
		Map<Long,TwaDocAsnHeader> headers=new HashMap<Long,TwaDocAsnHeader>();
		Map<String,String> docs=new HashMap<String,String>();
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
				det=service.findById(id);
				msg=service.canReceive(det, id);
				if (!StringUtils.isNullOrBlank(msg)){
					addErrorMessage(redirectAttributes, "收货失败:"+msg);
					return super.redirect("");
				}
				contnum=det.getContainNumber();
				if (StringUtils.isNullOrBlank(contnum)){
					addErrorMessage(redirectAttributes, "订单行的托盘码为空,行号="+det.getLineNumber());
					return super.redirect("");
				}
				conts.add(contnum);
				header=headers.get(det.getHeaderId());
				if (header==null){
					header=det.getHeader();
					if (header!=null){
						headers.put(header.getId(), header);
					}
				}
				if (header!=null){
					docs.put(contnum, header.getDocumentNumber());
				}
			}
		}
		try {
			String doc="";
			for (String cont : conts) {
				doc=docs.get(cont);
				msg=this.service.receive(doc, cont,"","","","","","","","",SecurityUtils.getLoginUsername());
				if(!msg.equals(CodesConstants.COMMON_STATUS_SUCCESS)){
					addErrorMessage(redirectAttributes, "收货失败:"+msg);
					failed=true;
					break;
				}
			}
			if (!failed){
				addSuccessMessage(redirectAttributes, "收货数据成功");
			}
		} catch (Exception e) {
			log.error("收货失败", e);
			addErrorMessage(redirectAttributes, "收货失败");
		}
		return super.redirect("");
	}


	@PostMapping("palletize")
	public String palletizeByDocLines(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
									RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";

		if ((ids==null) || (ids.length==0)){
            addErrorMessage(redirectAttributes, "请指定待码盘的单证行");
            return super.redirect("");
        }
        TwaDocAsnDetails line=null;
        TwaDocAsnHeader header=null;
        BigDecimal qtypal=BigDecimal.ZERO;
        String batchnum="";
        PalletizeActionDto actionDto=null;
        List<TwtActPalletizeList> palletizedata=null;
        TwmBasLocation loc=null;
        String worker=SecurityUtils.getLoginUsername();
        for (Long id : ids) {
            line=service.findById(id);
            if (line==null){
                addErrorMessage(redirectAttributes, "找不到单证行,请确认是否已删除.ID:"+String.valueOf(id));
                return super.redirect("");
            }
            if (WmsConstants.ASN_STATUS_CLOSE.equalsIgnoreCase(line.getLineStatus())){
                continue;
            }
            if (WmsConstants.ASN_STATUS_CANCELL.equalsIgnoreCase(line.getLineStatus())){
                continue;
            }
            if (WmsConstants.ASN_STATUS_RECEIVE.equalsIgnoreCase(line.getLineStatus())){
                continue;
            }
            qtypal=BigDecimal.ZERO;
            if (line.getQtyPalletized()!=null){
                qtypal=line.getQtyPalletized();
            }
            if (qtypal.compareTo(line.getQtyOrdered())>=0){
                continue;
            }
            header=this.headerService.findById(line.getHeaderId());
            if (header==null){
                addErrorMessage(redirectAttributes, "找不到单证,请确认是否已删除.ID:"+String.valueOf(line.getHeaderId()));
                return super.redirect("");
            }
            if (WmsConstants.ASN_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
                continue;
            }
            if (WmsConstants.ASN_STATUS_CANCELL.equalsIgnoreCase(header.getStatus())){
                continue;
            }
            if (WmsConstants.ASN_STATUS_RECEIVE.equalsIgnoreCase(header.getStatus())){
                continue;
            }
            //
            loc=null;
            if (line.getReceiveLocId()!=null){
                loc=this.locationService.findById(line.getReceiveLocId());
            }
            batchnum= TextUtils.genBatchNumber();
            actionDto=new PalletizeActionDto();
            palletizedata =this.palletizeService.palletize(batchnum,header,line,loc,actionDto);
            if ((palletizedata==null) || (palletizedata.size()==0)){
                continue;
            }
			try{
				this.palletizeService.update(palletizedata);
			}catch (Exception e){
				e.printStackTrace();
			}
            //
            this.palletizeService.updateDocline(palletizedata,line,worker);
			this.headerService.refreshStatus(header.getId());
        }
        String asnid="";
        Long headerid=null;
        if (header!=null){
            headerid=header.getId();
        }
        if ((headerid==null)&&(line!=null)){
            headerid=line.getHeaderId();
        }
        if (headerid!=null){
            asnid=String.valueOf(headerid);
        }
        model.addAttribute("headerId", headerid);

        return super.redirect(""+"/"+asnid);
		//return super.redirect("");
	}

	@PostMapping("recvbycontain")
	public String receive(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		Set<String> conts=new HashSet<String>();
		TwaDocAsnDetails det=null;
		TwaDocAsnHeader header=null;
		String contnum="";
		Map<Long,TwaDocAsnHeader> headers=new HashMap<Long,TwaDocAsnHeader>();
		Map<String,String> docs=new HashMap<String,String>();
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
				det=service.findById(id);
				msg=service.canReceive(det, id);
				if (!StringUtils.isNullOrBlank(msg)){
					addErrorMessage(redirectAttributes, "收货失败:"+msg);
					return super.redirect("");
				}
				contnum=det.getContainNumber();
				if (StringUtils.isNullOrBlank(contnum)){
					addErrorMessage(redirectAttributes, "订单行的托盘码为空,行号="+det.getLineNumber());
					return super.redirect("");
				}
				conts.add(contnum);
				header=headers.get(det.getHeaderId());
				if (header==null){
					header=det.getHeader();
					if (header!=null){
						headers.put(header.getId(), header);
					}
				}
				if (header!=null){
					docs.put(contnum, header.getDocumentNumber());
				}
			}
		}
		try {
			String doc="";
			for (String cont : conts) {
				doc=docs.get(cont);
				msg=this.service.receive(doc, cont,"","","","","","","","",SecurityUtils.getLoginUsername());
				if(!msg.equals(CodesConstants.COMMON_STATUS_SUCCESS)){
					addErrorMessage(redirectAttributes, "收货失败:"+msg);
					failed=true;
					break; 
				}
			}
			if (!failed){
				addSuccessMessage(redirectAttributes, "收货数据成功");
			}
		} catch (Exception e) {
			log.error("收货失败", e);
			addErrorMessage(redirectAttributes, "收货失败");
		}
		return super.redirect("");
	}
    
	@Override
	public String save(Model model, T m, BindingResult result, HttpServletRequest request,
                       RedirectAttributes redirectAttributes) {

		Object headerId = getParamValue(request, "headerId");
        TwaDocAsnHeader header =this.getHeader(request);
        model.addAttribute("r", header);
        
        //m.setHeaderId(header.getId());
        this.saveSetHeaderId(m, header.getId());
        
        // 设置默认值：
        /***
        Double requiredQty = null == m.getRequiredQty() ? 0 : m.getRequiredQty();
		Double packageQty = m.getPQty();
		Double reqBoxNum = Math.ceil(requiredQty/packageQty);
		requiredQty = reqBoxNum * packageQty;
		m.setRequiredQty(requiredQty);
		m.setReqBoxNum(reqBoxNum);
        
        if (null != m.getSendQty()) {
            m.setSendQty(m.getRequiredQty());
        }
		**/
        boolean isNew = false;
        if (null == this.getId(m)) {
            isNew = true;
        }
        String appendUrl = super.save(model, m, result, request, redirectAttributes);
        String msg="";
        if (isNew) {
            //service.save(m);
			msg = this.checkCleanStorages(header.getDeliveryContainerNum());
			if (!StringUtils.isNullOrBlank(msg)){
                this.addErrorMessage(redirectAttributes, msg);
                if (StringUtils.startsWith(appendUrl, "redirect:")) {
                    if (headerId != null) {
                        appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
                    }
                }
                return appendUrl;
            }
			this.createPalletize(m, header);
        }
		if (StringUtils.startsWith(appendUrl, "redirect:")) {
			if (headerId != null) {
				appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
			}
		}
		return appendUrl;
	}

	protected String checkCleanStorages(String containNumber){
		String m = "";
		if (StringUtils.isNullOrBlank(containNumber)){
			return m;
		}
        containNumber=containNumber.trim();
		List<TwaInventoryDetails> storages=null;
		try{
			storages=this.inventoryService.findByContainNumber(containNumber);
			if ((storages==null)||(storages.size()==0)){
			    return m;
            }
            for (TwaInventoryDetails d:storages){
			    if (d==null){
			        continue;
                }
                if (d.getMaterialId().equals(XcmgAmConstants.MATERIAL_ID_EPAL)){
                    this.inventoryService.delete(d);
                    continue;
                }
                m = "托盘已有库存.请确认是否托盘码重复.托盘码:"+containNumber;
                break;
            }
		}catch (Exception e){
            e.printStackTrace();
		}
		return m;
	}

	protected String createPalletizeByDetails(TwaDocAsnDetails line, TwaDocAsnHeader header){
		String m = "";
		if (line==null){
			return m;
		}
		if (header==null){
			return m;
		}
		if (StringUtils.isNullOrBlank(header.getDeliveryContainerNum())){
			return m;
		}
		List<TwtActPalletizeList> pals=null;
		TwtActPalletizeList pal=null;
		PalletizeChangeData palletizeData=null;
		TwmBasMaterial material=null;
		TaskActionDto actionDto=null;
		try{
			pals=this.palletizeService.findByContainNumber(header.getDeliveryContainerNum().trim());
			if ((pals!=null)&&(pals.size()>0)){
				for (TwtActPalletizeList p:pals){
					if (p==null){
						continue;
					}
					if ((p.getDocumentDetailsId()!=null)
							&& (p.getDocumentDetailsId().equals(line.getId()))){
						pal=p;
						break;
					}
				}
			}
			if (pal!=null){
				return m;
			}
			material=this.materialService.lookup(line.getMaterialId());
			//
			palletizeData=new PalletizeChangeData();
            palletizeData.setBatchnumber(TextUtils.genBatchNumber());
			palletizeData.setDivisioncode(this.divisionService.retrieve(header.getDivisionId()));
            palletizeData.setCustomercode(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM);
            palletizeData.setMaterialcode(line.getMaterialCode());
            palletizeData.setQuantity(line.getQtyOrdered());
            palletizeData.setLocationcode(XcmgAmConstants.LOCATION_CODE_PA0101);
            palletizeData.setLotattr05(this.customWorkService.defLotnumber());
            palletizeData.setLotattr06(XcmgAmConstants.XCMG_AE_CUSTOMER_CODE);
            palletizeData.setLotattr07(line.getLotattr07());
            palletizeData.setReservenumber(line.getLotattr07());
            palletizeData.setContainnumber(header.getDeliveryContainerNum());
            palletizeData.setTracenumber(palletizeData.getContainnumber());
            palletizeData.setCreatesource(CodesConstants.SYSTEM_WMS);
            palletizeData.setCreatetype(header.getCategory());
            palletizeData.setUdf01(line.getUdf01());
            palletizeData.setUdf02(line.getUdf02());
            palletizeData.setUdf03(line.getUdf03());
            palletizeData.setUdf04(line.getUdf04());
            palletizeData.setUdf05(line.getUdf05());
            palletizeData.setUdf06(line.getUdf06());
            palletizeData.setUdf07(line.getUdf07());
            palletizeData.setUdf08(line.getUdf08());
            palletizeData.setUdf09(line.getUdf09());
            palletizeData.setUdf10(line.getUdf10());

			actionDto=new TaskActionDto();
			pal=this.customWorkService.createPalletizeData(palletizeData, header, line, material, actionDto);
		}catch (Exception e){
			e.printStackTrace();
		}
		return m;
	}

	protected abstract void saveSetHeaderId(T d, Long headerId);

    protected abstract ID getId(T t);

    protected abstract TwaDocAsnDetails findById(ID id);


    @GetMapping("check/linenumber")
    @ResponseBody
    public boolean checkLinenumber(@RequestParam("lineNumber") String linenumber,
            @RequestParam("oldLinenumber") String oldLinenumber, @RequestParam("headerId") Long headerId) {
        if (null != oldLinenumber && oldLinenumber.equals(linenumber == null ? null : linenumber.toString())) {
            return true;
        }
        return service.countByLineNumberAndHeaderId(linenumber, headerId) <= 0;
    }

    @GetMapping("check/material")
    @ResponseBody
    public boolean checkPart(@RequestParam("material") Long materialId, @RequestParam("oldMaterial") String oldMaterialId,
            @RequestParam("headerId") Long headerId) {
        if (null != oldMaterialId && oldMaterialId.equals(materialId == null ? null : materialId.toString())) {
            return true;
        }
        return service.countByMaterialIdAndHeaderId(materialId, headerId) <= 0;
    }

	@PostMapping("del/{id}")
	@Override
    @GetMapping({"del/{id}"})
	public String del(@PathVariable("id") ID id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        Object headerId = getParamValue(request, "headerId");
    	String appendUrl = super.redirect("");
        if ((StringUtils.startsWith(appendUrl, "redirect:")) && (headerId != null) && (!StringUtils.isNullOrBlank(headerId.toString()))) {
            appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
        }
		model.addAttribute("params", getParams(request));
		String msg="";
		if (id!=null) {
			msg=this.delete(id);
			if (StringUtils.isNullOrBlank(msg)){
				addSuccessMessage(redirectAttributes, "删除数据成功");
			}else{
				addErrorMessage(redirectAttributes, "删除数据失败:"+msg);
			}
		}
		return appendUrl;
	}
	
    @Override
    public String del(@RequestParam("ids") ID[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        Object headerId = getParamValue(request, "headerId");
    	String appendUrl = super.redirect("");
        if ((StringUtils.startsWith(appendUrl, "redirect:")) && (headerId != null) && (!StringUtils.isNullOrBlank(headerId.toString()))) {
            appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
        }
		model.addAttribute("params", getParams(request));
		String msg="";
		if (ids != null && ids.length > 0) {
			try {
				for (ID id : ids) {
					msg=this.delete(id);
					if (!StringUtils.isNullOrBlank(msg)){
						addErrorMessage(redirectAttributes, "删除数据失败:"+msg);
						return appendUrl;
					}
				}
				addSuccessMessage(redirectAttributes, "删除数据成功");
			} catch (Exception e) {
				addErrorMessage(redirectAttributes, "删除数据失败");
			}
		}
		return appendUrl;
    }

	@PostMapping("print")
	public String printLabel(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
						  RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		TwaDocAsnDetails line=null;
		TwaDocAsnHeader header=null;
		String printercode="";
		Long templateid=1000100210030L;
		InventoryLabelDto labelDto;
        TwtActTaskPrintData printData=null;
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
                line=service.findById(id);
                msg=service.canPrint(line,id);
                if (!StringUtils.isNullOrBlank(msg)){
                    addErrorMessage(redirectAttributes, "打印失败:"+msg);
                    return super.redirect("");
                }
                labelDto=copy(line);
                if (labelDto==null){
                    continue;
                }
                labelDto.setTemplateid(templateid);
                labelDto.setPrintercode(printercode);
                printData=this.copy(labelDto);
                if (printData==null){
                    continue;
                }
                this.printTaskService.save(printData);
			}
		}
		return super.redirect("");
	}
    
    private String delete(ID id){
    	String msg="";
    	if (id==null){
    		return msg;
    	}
        String flag=null;
    	TwaDocAsnHeader header=null;
    	List<TwtActPalletizeList> pals=null;
    	List<TwtActTaskList> tasks=null;
    	TwtActPalletizeList pal=null;
    	try{
    		TwaDocAsnDetails details=this.findById(id);
    		if (details==null){
    			msg="找不到订单明细,请确认是否已删除.单证行ID="+String.valueOf(id);
    			return msg;
    		}
    		if (!WmsConstants.ASN_STATUS_CREATE.equals(details.getLineStatus())){
    			msg="单证明细非创建状态,不能删除.当前状态:"+details.getLineStatus();
    			return msg;
    		}
    		if ((details.getQtyReceivedEach()!=null) && (details.getQtyReceivedEach().compareTo(BigDecimal.ZERO)>0)){
    			msg="单证明细已经收货,不能删除.收货数量:"+String.valueOf(details.getQtyReceivedEach());
    			return msg;
    		}
    		if ((details.getQtyPalletizedEach()!=null) && (details.getQtyPalletizedEach().compareTo(BigDecimal.ZERO)>0)){
    			msg="单证明细已经码盘,不能删除.码盘数量:"+String.valueOf(details.getQtyPalletizedEach());
    			return msg;
    		}
            header=this.getHeader(details.getHeaderId());
            flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_ASN);
            if  (CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag)) {
                if  ((header!=null)&& (!WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
                    msg = "单证已经开始作业，不能修改!";
                    return msg;
                }
            }
            if (!StringUtils.isNullOrBlank(header.getDeliveryContainerNum())){
                tasks=this.taskService.queryWorkingTasks("", header.getDeliveryContainerNum().trim());
                if ((tasks==null)||(tasks.size()==0)){
                    pals=this.palletizeService.findByContainNumber(header.getDeliveryContainerNum().trim());
                    if ((pals!=null)&&(pals.size()>0)){
                        for (TwtActPalletizeList p:pals){
                            if (p==null){
                                continue;
                            }
                            if ((p.getDocumentDetailsId()!=null)
                                    && (p.getDocumentDetailsId().equals(details.getId()))){
                                this.palletizeService.delete(p);
                            }
                        }
                    }
                }
            }
    		this.service.delete(details);
    	}catch(Exception e){
    		msg="删除订单明细异常:"+e.getMessage();
    	}
    	return msg;
    }    
    private TwaDocAsnHeader getHeader(HttpServletRequest request){
		Object headerId = getParams(request).get("headerId");
		return this.getHeader(headerId);
    }

    protected TwaDocAsnHeader getHeader(Map<?,?> params){
		Object headerId = params.get("headerId");
		return this.getHeader(headerId);
    }
    
    private TwaDocAsnHeader getHeader(Object headerId){
    	TwaDocAsnHeader header = new TwaDocAsnHeader();
		if (null != headerId && StringUtils.isNotBlank(headerId.toString())) {
			header = headerService.getById(Long.valueOf(headerId.toString()));
		}
		return header;
    }

    private InventoryLabelDto copy(TwaDocAsnDetails line){
		InventoryLabelDto labelDto=null;
		if (line==null){
			return labelDto;
		}
        labelDto=new InventoryLabelDto();
		//Palletized-id
		labelDto.setTRANS_ID(String.valueOf(line.getId()));
		labelDto.setMAT_CODE(line.getMaterialCode());
		labelDto.setMAT_NAME(line.getMaterialName());
		labelDto.setLOT_NUM(line.getLotattr05());
		labelDto.setORDER_QTY(String.valueOf(line.getQtyOrderedEach()));
		labelDto.setPAL_QTY("1");
		labelDto.setCARTON_QTY("1");
		try{
            String docnum="";
		    TwaDocAsnHeader header=line.getHeader();
		    if (header!=null){
                docnum=header.getDocumentNumber();
                labelDto.setGlobalClientid(header.getGlobalClientId());
                labelDto.setDivisionId(header.getDivisionId());
                labelDto.setCustomerId(header.getCustomerId());
            }
            labelDto.setDocumentnumber(docnum);
            labelDto.setDocumentlinenumber(line.getLineNumber());
            labelDto.setMAT_FULL_TEXT(labelDto.getMAT_CODE()+"/"+labelDto.getLOT_NUM()+"/"+labelDto.getDocumentnumber()+"/"+labelDto.getDocumentlinenumber());
        }catch (Exception e){
        }
        return labelDto;
	}

	private TwtActTaskPrintData copy(InventoryLabelDto labelDto){
        TwtActTaskPrintData printData=null;
        if (labelDto==null){
            return printData;
        }
        String batno= TextUtils.genBatchNumber();
        printData=new TwtActTaskPrintData();
        printData.setGlobalClientId(labelDto.getGlobalClientid());
        printData.setDivisionId(labelDto.getDivisionId());
        printData.setCustomerId(labelDto.getCustomerId());

        printData.setBatchNumber(batno);
        printData.setDocumentNumber(labelDto.getDocumentnumber());

        printData.setPrinterCode(labelDto.getPrintercode());
        printData.setTemplateId(labelDto.getTemplateid());
        printData.setPrintData(labelDto.getMAT_FULL_TEXT());
        printData.setPrintStatus(CodesConstants.COMMON_STATUS_CREATED);
        printData.setCopies(1);

        printData.setCreatedDate(new Date());
        printData.setCreatedBy(SecurityUtils.getLoginUsername());
        printData.setLastModifiedDate(new Date());
        printData.setLastModifiedBy(SecurityUtils.getLoginUsername());

        return printData;
    }
    
    /**
    private Long getHeaderId(HttpServletRequest request){
		Long headerId=null; 
    	Map<?, ?> params=getParams(request);
    	if (params==null){
    		return headerId;
    	}
		Object asnId = params.get("asnId");
		if (null != asnId && StringUtils.isNotBlank(asnId.toString())) {
			headerId=Long.parseLong(asnId.toString());
		}
		return headerId;
    }
	**/

    protected String createPalletize(T t, TwaDocAsnHeader header){
    	return "";
	}
}
